namespace OFX.Aggregator.Implementation.BESnet
{
	#region #using Directives

	using System.Globalization;
	using System.Linq;
	using System.Text.RegularExpressions;
	using System.Web;

	using Infrastructure;

	#endregion

	public abstract class StatementInterpreterBase : IStatementInterpreter
	{
		protected CultureInfo cultureInfo = CultureInfo.CurrentCulture;
		protected IRegexPatternProvider regexProvider;

		protected StatementInterpreterBase(string culture, IRegexPatternProvider regexProvider)
		{
			this.regexProvider = regexProvider;
			this.cultureInfo = CultureInfo.GetCultureInfo(culture);
		}

		#region IStatementInterpreter Members

		public abstract Statement InterpretStatement(string input);

		#endregion

		protected double RetrieveMatchValueAsCurrency(Match match, string captureName)
		{
			var numberFormatInfo = this.cultureInfo.NumberFormat;

			string str = RetrieveMatchValue(match, captureName).Trim().Split(new[] {' '}).First();
			double amount = (str == "-" ? 0.0 : double.Parse(str, NumberStyles.Currency, numberFormatInfo));

			return amount;
		}

		protected static string RetrieveMatchValue(Match match, string captureName)
		{
			string value = HttpUtility.HtmlDecode(match.Groups[captureName].Value);
			const RegexOptions options =
				RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline | RegexOptions.Multiline | RegexOptions.IgnoreCase | RegexOptions.Compiled;

			value = Regex.Replace(value, @"<(?<tag>\w).*?>(?<content>.*)</\k<tag>>", "${content}", options);

			return value;
		}
	}
}